var sign = getQueryString("sign");
var GET_LIST = "/data/changjiaSign/";//获取列表
var GET_DETAILS = "/data/changjia/";//获取详情
var genreColor1 = "#6f60aa";//genre1 颜色
var genreColor2 = "#45b97c";//genre2 颜色
var genreColor3 = "#00a6ac";//genre3 颜色
var genreColor4 = "#d64f44";//genre4 颜色
var count = 0;
var MODIF_URL = "/data/changjia/";
var DELETE_URL = "/data/changjiaDelete/";//永久删除


$(function () {
    'use strict';
    //无限滚动
    $(document).on("pageInit", "#page-infinite-scroll-bottom", function(e, id, page) {
        var loading = false;
        var lastIndex = 13;

        $(page).on('infinite', function() {
            // 如果正在加载，则退出
            if (loading) return;
            // 设置flag
            loading = true;
            lastIndex = document.getElementById("content").childElementCount;
            // 模拟1s的加载过程
            setTimeout(function() {
                // 重置加载flag
                loading = false;
                addItems((lastIndex-3));
                // 更新最后加载的序号
                $.refreshScroller();
            }, 1000);
        });
    });

    $(document).on('click','.buttonDelete', function (even) {
        $.confirm('Are you sure?',
            function () {
                $.alert('确定删除吗?');
                a_none_onclick_delete(even.currentTarget);
            }
        );
    });

    $.init();
    window.onload=function(){
        addItems(0);
        ready();
    };
});

var ready = function () {
    modifyTitle();
};
var modifyTitle = function () {
    var str;
    switch (sign){
        case "1": str = "无效客户"; break;
        case "8": str = "有效客户"; break;
        case "9": str = "优质客户"; break;
    }
    document.getElementsByClassName("title")[0].innerHTML = str;
};

var a_none_onclick_toRouter = function (t) {
    ajax({
        type:"GET",
        url:GET_DETAILS+t.dataset.id,
        dataType:"json",
        success:function(data){
            if (data.code == 200){
                d = data.data;

                var card = document.getElementById("card");
                card.getElementsByTagName("form")[0].id = d.id;

                card.getElementsByClassName("card-header")[0].innerHTML = d.company;
                var inputs = card.getElementsByTagName("input");
                inputs[0].value = d.company;
                inputs[1].value = d.address;
                inputs[2].value = d.type;
                inputs[3].value = d.linkman;
                inputs[4].value = d.phone;
                inputs[5].value = d.telephone;
                inputs[6].value = d.linkman2;
                inputs[7].value = d.phone2;
                card.getElementsByTagName("textarea")[0].value = d.remark;
                card.getElementsByTagName("a")[0].href = "tel:"+d.phone;
                card.getElementsByTagName("a")[1].href = "tel:"+d.telephone;
                card.getElementsByTagName("a")[2].href = "tel:"+d.phone2;

                // card.getElementsByClassName("buttons-row")[0].firstElementChild.href = "/data/changjia/"+d.id;
                // card.getElementsByClassName("buttons-row")[0].lastElementChild.href = "/data/changjia/"+d.id;
                put = card.getElementsByClassName("button-success")[0];
                console.log(put);
                put.dataset.id = d.id;

                putA = card.getElementsByClassName("buttons-row")[0].lastElementChild;
                putA.dataset.id = d.id;

                putB = card.getElementsByClassName("buttons-row")[0].firstElementChild;
                putB.dataset.id = d.id;

                changeRgb(card.getElementsByClassName("card-header")[0]);
                //加载完毕绑定事件
                put.onclick = function (putA) {//绑定优质按钮
                    clientPOST(this);
                    console.log("A")
                };
                putA.onclick = function () {//绑定有效按钮
                    clientPut(this);
                };
                putB.onclick = function () {//绑定拉黑按钮
                    clientDelete(this)
                };
                $.router.load('#router3');
            }else if (data.code == 201){
            } else if (data.code == 500){
                window.location.href = "/login.html";
            }
        },
        error:function (data) {
            $.toast("加载失败");
        }

    });
    // return false;
};

var a_none_onclick_delete = function (t) {
    $.ajax({
        url: DELETE_URL+ t.dataset.id, /*url也可以是json之类的文件等等*/
        type: 'DELETE', /*DELETE、POST */
        data: {
            "_method": "DELETE"
        },
        success: function (result) {
            if (result.code == 200) {
                $.toast("删除成功");
            } else {
                $.toast("拉黑可能失败了~");
            }
        }
    })
};


function addItems(lastIndex) {
    ajax({
        type:"GET",
        url:GET_LIST+sign+"?item="+lastIndex,
        dataType:"json",
        success:function(data){
            if (data.code == 200){
                for (i=0; i<data.data.length; i++){
                    d = data.data[i];
                    addItem(d);
                }
            }else if (data.code == 201){
                if(count<=3){
                    $.toast("没拉 就这么多");
                }else if(count<=5){
                    $.toast("警告你,不要在拉了");
                }else if(count<=7){
                    $.toast("真的,没了");
                }else if(count<=8){
                    $.toast("真的...没了");
                }else if(count<=9){
                    $.toast("最后一次警告,没了");
                }else if(count<=10){
                    $.toast("最最后一次警告,真的没了");
                }else if(count<=11){
                    $.toast("再见吧");
                    window.location.href = "/logout";
                }
                count++;
            } else if (data.code == 500){
                window.location.href = "/login.html";
            }
        },
        error:function (data) {
            $.toast("加载失败");
        }
    })
}
//选择模板
var choiceTemplate = function () {
    temId = "sign"+sign;
    var Tem = document.getElementById(temId).cloneNode(true);
    Tem.style.display = "block";
    Tem.getElementsByClassName("item-inner")[0].color = "#FFF";
    return Tem;
};
//增加一列
var addItem = function (data) {
    var Tem = choiceTemplate();
    Tem.id = data.id;
    var items = Tem.getElementsByClassName("item-inner");
    items[0].lastElementChild.innerHTML = data.company;
    items[1].lastElementChild.innerHTML = data.linkman;
    items[2].lastElementChild.firstElementChild.innerHTML = data.phone;
    items[2].lastElementChild.lastElementChild.href = "tel:"+data.phone;

    // items[0].parentElement.href = GET_DETAILS+data.id;
    var A = items[0].parentElement;
    A.href = "#";
    A.dataset.id = data.id;
    A.onclick=function () {
        a_none_onclick_toRouter(this);
    };
    console.log(A);

    var color;
    switch (data.genre){
        case 1: color = genreColor1; break;
        case 2: color = genreColor2; break;
        case 3: color = genreColor3; break;
        case 4: color = genreColor4; break;
    }
    items[0].parentElement.parentElement.style.backgroundColor = color;


    /*删除按钮*/

    var buttonDelete = Tem.getElementsByClassName("button button-warning buttonDelete")[0];
    if (buttonDelete)
        buttonDelete.dataset.id = data.id;


    document.getElementById("content").append(Tem);
};

//修改信息->标记为有效客户
function clientPut(node) {
    objId = node.dataset.id;
    console.log(node);
    from = document.getElementById("card").firstElementChild;
    var inputs = from.getElementsByTagName("input");

    $.ajax({
        url:MODIF_URL+objId,/*url也可以是json之类的文件等等*/
        type:'POST',/*DELETE、POST */
        data:{
            "_method" : "PUT",
            "id" : objId,
            "company" : inputs[0].value,
            "address" : inputs[1].value,
            "type" : inputs[2].value,
            "linkman" : inputs[3].value,
            "phone" : inputs[4].value,
            "telephone" : inputs[5].value,
            "linkman2" : inputs[6].value,
            "phone2" : inputs[7].value,
            "remark" : from.getElementsByTagName("textarea")[0].value
        },
        contentType : "application/x-www-form-urlencoded;charset=UTF-8",
        success:function (result) {
            if(result.code == 200){
                result.data == 1 ? $.toast("标记成功") : $.toast("某些原因导致标记失败了~");
            }else {
                $.toast("被某人抢先标记了~");
            }
        }
    })
}

function clientDelete(node) {
    objId = node.dataset.id;

    $.ajax({
        url: MODIF_URL+ objId, /*url也可以是json之类的文件等等*/
        type: 'POST', /*DELETE、POST */
        data: {
            "_method": "DELETE",
            "id": objId
        },
        success: function (result) {
            if (result.data == 1) {
                $.toast("拉黑成功");
            } else {
                $.toast("拉黑可能失败了~");
            }
        }
    })
}

function clientPOST(node) {
    objId = node.dataset.id;

    $.ajax({
        url: MODIF_URL + objId, /*url也可以是json之类的文件等等*/
        type: 'POST', /*DELETE、POST */
        data: {
            "_method": "POST",
            "id": objId
        },
        success: function (result) {
            if (result.data == 1) {
                $.toast("标记成功,他是你的了");
            } else {
                $.toast("标记失败,可能被抢先了");
            }
        }
    })
}




















/*文本框自适应*/
function setHeight(element) {
    $(element).css({'height':'auto','overflow-y':'hidden','background-color':'#f5f5f5;margin-left: 0.13rem;'}).height(element.scrollHeight);}
$('textarea').each(function () {
    setHeight(this);
}).on('input', function () {
    setHeight(this);
});
/*随机颜色*/
changeRgb = function (cardHeader) {
    cardHeader.style.backgroundColor = rgb();
    if (rgbSum < 400) {
        cardHeader.style.color = "#FFF";
    }
};
function rgb(){
    var r=Math.floor(Math.random()*255);
    var g=Math.floor(Math.random()*255);
    var b=Math.floor(Math.random()*255);
    var rgb='rgb('+r+','+g+','+b+')';
    rgbSum = r+g+b;
    return rgb;
}
/*手写ajax*/
function ajax(){
    var ajaxData = {
        type:arguments[0].type || "GET",
        url:arguments[0].url || "",
        async:arguments[0].async || "true",
        data:arguments[0].data || null,
        dataType:arguments[0].dataType || "text",
        contentType:arguments[0].contentType || "application/x-www-form-urlencoded",
        beforeSend:arguments[0].beforeSend || function(){},
        success:arguments[0].success || function(){},
        error:arguments[0].error || function(){}
    };
    ajaxData.beforeSend();
    var xhr = createxmlHttpRequest();
    xhr.responseType=ajaxData.dataType;
    xhr.open(ajaxData.type,ajaxData.url,ajaxData.async);
    xhr.setRequestHeader("Content-Type",ajaxData.contentType);
    xhr.send(convertData(ajaxData.data));
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            if(xhr.status == 200){
                ajaxData.success(xhr.response)
            }else{
                ajaxData.error()
            }
        }
    }
}
function createxmlHttpRequest() {
    if (window.ActiveXObject) {
        return new ActiveXObject("Microsoft.XMLHTTP");
    } else if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    }
}
function convertData(data){
    if( typeof data === 'object' ){
        var convertResult = "" ;
        for(var c in data){
            convertResult+= c + "=" + data[c] + "&";
        }
        convertResult=convertResult.substring(0,convertResult.length-1)
        return convertResult;
    }else{
        return data;
    }
}
//获取参数地址栏参数
function getQueryString(name) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return unescape(r[2]);
    }
    return null;
}
